package com.soap.interceptor;

import com.soap.entities.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/4/17 20:26
 */
@Slf4j
public class CheckUserInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private final static String QNAME_SPACE = "http://crscd.com.cn/auth";
    private final static String USER_NAME = "db.username";
    private final static String USER_LAN = "language";
    private final static String USER_STATION = "station";
    private final static String USER_IP_ADDRESS = "ipAddress";

    public CheckUserInterceptor() {
        //在执行webmethod方法之前调用
        super(Phase.PRE_INVOKE);
    }

    /**
     * 根据约定从header中取出数据，前提是指定属性只能有一个，否则会出现覆盖
     *
     * @param element
     * @param targetElement
     * @return
     */
    private static String getHeaderValue(Element element, String targetElement) {
        if (null == element || null == targetElement) {
            return null;
        }
        // 取出<auth>标签指定名称的文本节点信息
        return element.getElementsByTagName(targetElement).item(0).getTextContent();
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        log.info("Server handleMessage");
        // 从请求消息中取出用户名和自定义信息
        final Header auth = message.getHeader(new QName(QNAME_SPACE, "auth"));
        if (auth != null) {
            Element element = (Element) auth.getObject();
            final String username = getHeaderValue(element, USER_NAME);
            final String language = getHeaderValue(element, USER_LAN);
            final String station = getHeaderValue(element, USER_STATION);
            final String ip = getHeaderValue(element, USER_IP_ADDRESS);

            UserInfo userInfo = new UserInfo(username, language, station, ip);
            System.out.println("user info in soap header:" + userInfo);
        }
    }
}
